package com.hctforgreen.greenservice.examine;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ParentActivity;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbExamController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.ExamPaperEntity;
import com.hctforgreen.greenservice.model.ExamPaperEntity.PAPER_TYPE;
import com.hctforgreen.greenservice.model.ExamSubEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.ResultEntity;
import com.hctforgreen.greenservice.service.HctApplication;
import com.hctforgreen.greenservice.ui.adapter.NotYetListAdapter;
import com.hctforgreen.greenservice.utils.ContantsUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;

import java.text.DecimalFormat;
import java.util.List;

/**
 * 查看已做未做
 *
 * @author Tallen Zhai
 */
public class SeeNotYetActivity extends ParentActivity {

    private ExamPaperEntity mPaperEntity;

    private List<ExamSubEntity> examSubEntities;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.see_not_yet_activity);
        // Intent intent = getIntent();
        // AllExamListEntity listEntity =
        // (CountDownExamDetailActivity)intent.getSerializableExtra(HctConstants.ON_ACTIVITY_KEY_ALL_EXAM_LIST_ENTITY);
        initSkinLayout();
        initFinshExamineActivityReceiver();
        initTitleButtonBar();
        initWindow();
    }

    private void initTitleButtonBar() {
        final TextView titleTv = (TextView) findViewById(R.id.tv_title);
        titleTv.setText(getString(R.string.exam_answer_sheet));

        final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
        backBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 确定交卷
        final Button btnRight = (Button) findViewById(R.id.btn_right);
        btnRight.setText(getString(R.string.sheet_title_right));
        btnRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showMakeSureDialog();
            }
        });
        // InitTitle.initTitle(this, R.drawable.btn_reback, "查看未做", 0,
        // new OnClickListener() {
        // @Override
        // public void onClick(View v) {
        // finish();
        // }
        //
        // }, null);
    }

    private void initWindow() {
        examSubEntities = HctApplication.examSubEntities;
        if (examSubEntities == null || examSubEntities.isEmpty()) {
            return;
        }
        mPaperEntity = (ExamPaperEntity) getIntent().getSerializableExtra(
                HctConstants.ON_ACTIVITY_KEY_PAPER_ENTITY);
        HctApplication.examSubEntities = null;
        GridView notYetGv = (GridView) findViewById(R.id.gv_not_yet);
        new NotYetListAdapter(this, notYetGv, examSubEntities);
    }

    /**
     * 交卷提示框
     */
    private void showMakeSureDialog() {
        if (examSubEntities == null || examSubEntities.isEmpty()) {
            return;
        }
        List<ExamSubEntity> dataList = examSubEntities;
        int totalSize = dataList.size();
        for (ExamSubEntity ExamSubEntity : dataList) {
            if (isAlready(ExamSubEntity)) {
                totalSize--;
            }
        }
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(
                SeeNotYetActivity.this);
        builder.setTitle(R.string.dialog_default_title_hint);
        if (totalSize == 0) {
            /**
             * 已经全部做完
             */
            builder.setMessage(R.string.make_sure_dialog_content_total_hint);
        } else if (totalSize > 0) {
            builder.setMessage(getString(R.string.make_sure_dialog_content_header_hint) + totalSize + getString(R.string.make_sure_dialog_content_footer_hint));
        }
        builder.setNegativeButton(R.string.dialog_cancel_hint, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton(R.string.dialog_confirm_hint, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 提交试卷
                addSco();
            }
        });
        dialog = builder.create();
        dialog.show();

    }

    /**
     * 是否做完
     *
     * @param entity
     * @return
     */
    private boolean isAlready(final ExamSubEntity entity) {
        boolean bAlready = false;
        if (!entity.inputAnswer.equals("")) {
            bAlready = true;
        }
        if ((entity.inputAnswerList != null && entity.inputAnswerList.size() > 0)) {
            for (String sInputAnswer : entity.inputAnswerList) {
                if (!sInputAnswer.equals("")) {
                    bAlready = true;
                }
            }
        }
        return bAlready;
    }

    /**
     * 提交试卷
     */
    private void addSco() {
        try {
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setMessage(getString(R.string.dialog_add_sco_content_hint));

            @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
                public void handleMessage(Message msg) {
                    progressDialog.dismiss();
                    HctResult hctResult = new HctResult();
                    switch (msg.what) {
                        case HctConstants.STATUS_SUCCESS:
                            hctResult = (HctResult) msg.obj;
                            ResultEntity entity = (ResultEntity) hctResult.data;
                            if ("0".equals(entity.statusCode)) {
                                Toast.makeText(SeeNotYetActivity.this, "提交成功!", Toast.LENGTH_SHORT).show();
                                startResultsShowActivity();
                            } else {
                                Toast.makeText(SeeNotYetActivity.this, getString(R.string.net_error_hint), Toast.LENGTH_SHORT).show();
                            }
                            break;
                        case HctConstants.STATUS_FAILD:
                            Toast.makeText(SeeNotYetActivity.this, getString(R.string.net_error_hint), Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            };
            progressDialog.show();
            new Thread() {
                public void run() {
                    Message message = new Message();
                    try {
                        HctController controller = new HctController(SeeNotYetActivity.this);
                        LoginResultEntity loginResultEntity = LoginResultStoreUtil.get(SeeNotYetActivity.this);
                        DecimalFormat decimalFormat = new DecimalFormat("0");
                        ContantsUtil.isSubmitPaper = true;
                        HctResult result = controller.addSco(loginResultEntity.personId, mPaperEntity.id,
                                decimalFormat.format(getScore()), "", isPass() + "");
                        if (result.status == HctConstants.STATUS_SUCCESS) {
                            message.what = result.status;
                            message.obj = result;
                        } else {
                            message.what = HctConstants.STATUS_FAILD;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    handler.sendMessage(message);
                }
            }.start();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    private void startResultsShowActivity() {
        if (mPaperEntity.paperType == PAPER_TYPE.TYPE_CACHE) {
            new HandlerThread("delete_cahche") {
                public void run() {
                    DbExamController dbExamController = new DbExamController(
                            SeeNotYetActivity.this);
                    dbExamController.delete(mPaperEntity);
                    dbExamController.delete(examSubEntities);
                }

                ;
            }.start();
        }

        Intent intent = new Intent();
        intent.setClass(SeeNotYetActivity.this, ResultsShowActivity.class);
        // AllExamListEntity listEntity = new AllExamListEntity();
        // listEntity.dataList = mAdapter.getmEntities();
        // intent.putExtra(HctConstants.ON_ACTIVITY_KEY_ALL_EXAM_LIST_ENTITY,
        // listEntity);
        intent.putExtra(HctConstants.ON_ACTIVITY_KEY_PAPER_ENTITY, mPaperEntity);
        HctApplication.examSubEntities = examSubEntities;
        startActivityForResult(
                intent,
                HctConstants.ON_ACTIVITY_RESULT_NOT_YET_OR_SITUATION_LIST_ACTIVITY);
    }

    /**
     * 考试是否通过
     *
     * @return int ispass 0未通过 1通过
     */
    private int isPass() {
        int isPass = 1;
        if (getScore() < mPaperEntity.passScore) {
            isPass = 0;
        }

        return isPass;
    }

    /**
     * 获取分数
     */
    private double getScore() {
        if (examSubEntities == null || examSubEntities.isEmpty()) {

            return 0D;
        }
        // List<ExamSubEntity> dataList = mAdapter.getmEntities();
        /**
         * 分数
         */
        double iTotalScore = 0;
        for (ExamSubEntity ExamSubEntity : examSubEntities) {
            iTotalScore += Double.valueOf(ExamSubEntity.inputAnswerScore);
        }
        return iTotalScore;
    }

    private String getInputAnswerMsg() {
        String sInputAnswerMsg = "";
        List<ExamSubEntity> dataList = examSubEntities;
        for (int i = 0; i < dataList.size(); i++) {
            ExamSubEntity entity = dataList.get(i);
            String sTmpMsg = String.valueOf(entity.id) + ":";
            // =====================
            // 单选1 多选2 判断3 排序4
            // =====================
            /**
             * 单选
             */
            if (entity.type.equals("1")) {
                if (entity.inputAnswer.equals("")) {
                    sTmpMsg += "0";
                } else {
                    sTmpMsg += entity.inputAnswer;
                }
                sTmpMsg += "-1";
            }
            /**
             * 多选
             */
            else if (entity.type.equals("2")) {
                if (entity.inputAnswerList == null
                        || entity.inputAnswerList.size() <= 0) {
                    sTmpMsg += "0";
                } else {
                    for (String sInputAnswer : entity.inputAnswerList) {
                        if (sInputAnswer.equals("")) {
                            sTmpMsg += "0" + ";";
                        } else {
                            sTmpMsg += sInputAnswer + ";";
                        }
                    }
                }
                sTmpMsg += "-2";
            }
            /**
             * 判断
             */
            else if (entity.type.equals("3")) {
                if (entity.inputAnswer.equals("")) {
                    sTmpMsg += "0";
                } else {
                    sTmpMsg += entity.inputAnswer;
                }
                sTmpMsg += "-3";
            }
            /**
             * 排序
             */
            else if (entity.type.equals("4")) {
                if (entity.inputAnswerList == null
                        || entity.inputAnswerList.size() <= 0) {
                    sTmpMsg += "0";
                } else {
                    for (String sInputAnswer : entity.inputAnswerList) {
                        if (sInputAnswer.equals("")) {
                            sTmpMsg += "0" + ";";
                        } else {
                            sTmpMsg += sInputAnswer + ";";
                        }
                    }
                }
                sTmpMsg += "-4";
            }
            sInputAnswerMsg += sTmpMsg + "_";
        }
        /**
         * 截取最后1位的"_"
         */
        if (sInputAnswerMsg.length() > 0) {
            sInputAnswerMsg = sInputAnswerMsg.substring(0,
                    sInputAnswerMsg.length() - 1);
        }
        return sInputAnswerMsg;
    }
}
